package com.lottery.im.module.chat.ui;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.SectionProfile;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.SelectSearchProfileAdapter;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.module.tim.model.GroupProfile;
import com.lottery.im.module.tim.model.ProfileSummary;
import com.tencent.imsdk.TIMConversationType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 本地搜索（好友、已加入的群组）
 */
public class LocalSearchFragment extends BaseSwipeFragment {

  @BindView(R.id.et_search) EditText mEtSearch;
  @BindView(R.id.iv_clear) ImageView mIvClear;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.tv_empty_tip) TextView mTvEmptyTip;

  private List<FriendProfile> mFriendProfiles = new ArrayList<>();
  private List<GroupProfile> mGroupProfiles = new ArrayList<>();

  private List<SectionProfile> mProfiles;
  private SelectSearchProfileAdapter mAdapter;

  private String mStartId;
  private TIMConversationType mStartType;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_local_search;
  }

  @Override protected void initPresenter() {
    initView();
  }

  private void initView() {

    getFriends();
    getGroup();

    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);
    mProfiles = new ArrayList<>();
    mAdapter = new SelectSearchProfileAdapter(mProfiles);
    mAdapter.setOnItemClickListener((adapter, view, position) -> {
      if (mProfiles.get(position).isHeader) return;
      ProfileSummary profile = mProfiles.get(position).t;
      mStartId = profile.getIdentify();
      if (profile instanceof GroupProfile) {
        mStartType = TIMConversationType.Group;
      } else if (profile instanceof FriendProfile) {
        mStartType = TIMConversationType.C2C;
      }
      popBackStack();
    });
    mList.setAdapter(mAdapter);
  }

  @OnClick({ R.id.iv_clear, R.id.tv_cancel }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_clear:
        mEtSearch.setText("");
        break;
      case R.id.tv_cancel:
        popBackStack();
        break;
    }
  }

  @OnTextChanged(value = R.id.et_search, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
  void afterTextChanged(Editable content) {
    if (TextUtils.isEmpty(content.toString())) {
      mIvClear.setVisibility(View.GONE);
    } else {
      mIvClear.setVisibility(View.VISIBLE);
    }
    search(content.toString());
  }

  /**
   * 群成员搜索
   *
   * @param content 搜索内容
   */
  private void search(String content) {
    mProfiles.clear();
    if (TextUtils.isEmpty(content)) {
      mTvEmptyTip.setVisibility(View.GONE);
      mList.setVisibility(View.VISIBLE);
    } else {

      List<FriendProfile> searchFriends = new ArrayList<>();

      for (FriendProfile profile : mFriendProfiles) {
        if (profile.getName().contains(content) || profile.getIdentify().contains(content)) {
          searchFriends.add(profile);
        }
      }

      if (searchFriends.size() > 0) {
        mProfiles.add(new SectionProfile(true, "好友"));
        for (FriendProfile profile : searchFriends) {
          mProfiles.add(new SectionProfile(profile));
        }
      }

      List<GroupProfile> searchGroups = new ArrayList<>();

      for (GroupProfile profile : mGroupProfiles) {
        if (profile.getName().contains(content)) {
          searchGroups.add(profile);
        }
      }

      if (searchGroups.size() > 0) {
        mProfiles.add(new SectionProfile(true, "群组"));
        for (GroupProfile profile : searchGroups) {
          mProfiles.add(new SectionProfile(profile));
        }
      }

      if (mProfiles.size() == 0) {
        mTvEmptyTip.setVisibility(View.VISIBLE);
        mList.setVisibility(View.GONE);
      } else {
        mTvEmptyTip.setVisibility(View.GONE);
        mList.setVisibility(View.VISIBLE);
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  /**
   * 获取好友列表
   */
  private void getFriends() {
    mFriendProfiles.clear();
    Map<String, List<FriendProfile>> friends = FriendshipInfo.getInstance().getFriends();
    List<String> groupNames = FriendshipInfo.getInstance().getGroups();
    for (String groupName : groupNames) {
      for (FriendProfile friendProfile : friends.get(groupName)) {
        mFriendProfiles.add(friendProfile);
      }
    }
  }

  /**
   * 获取群组列表
   */
  private void getGroup() {
    List<GroupProfile> list = GroupInfo.getInstance().getGroupListByType(GroupInfo.publicGroup);
    for (GroupProfile summary : list) {
      mGroupProfiles.add(summary);
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();

    if (!TextUtils.isEmpty(mStartId)) {
      ChatActivity.navToChat(mActivity, mStartId, mStartType);
    }
  }
}
